package com.shuoyue.ycgk.ui.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.viewpager.widget.ViewPager;

import com.shuoyue.ycgk.BuildConfig;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.FileUtil;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.base.baseadapter.IndexFragmentAdapter;
import com.shuoyue.ycgk.download.DownloadManagerUtil;
import com.shuoyue.ycgk.entity.AppVersionInfo;
import com.shuoyue.ycgk.entity.MainAdv;
import com.shuoyue.ycgk.entity.UserInfo;
import com.shuoyue.ycgk.ui.common.download.DownloadContract;
import com.shuoyue.ycgk.ui.main.main_flowable.FragmentMainBaseType;
import com.shuoyue.ycgk.ui.mine.info.FragmentMe;
import com.shuoyue.ycgk.ui.mycourse.FragmentMyCourse;
import com.shuoyue.ycgk.ui.news.FragmentMainNewsType;
import com.shuoyue.ycgk.ui.recruitment.FragmentNotice;
import com.shuoyue.ycgk.utils.AppUtil;
import com.shuoyue.ycgk.utils.NOpenFiles;
import com.shuoyue.ycgk.utils.XToast;
import com.shuoyue.ycgk.views.dialog.AdvertisementDialog;
import com.shuoyue.ycgk.views.dialog.NewVersionDialog;
import com.shuoyue.ycgk.views.dialog.common.HintConfirmDialog;
import com.shuoyue.ycgk.views.viewpager_scroll.SuperViewPager;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.commonsdk.debug.D;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainTabActivity extends BaseMvpActivity implements MainAdvContract.View, DownloadContract.View, VersionContract.View {

    List<BaseMvpFragment> fragmentList = new ArrayList<>();
    FragmentMainBaseType fragmentMainTab;
    FragmentMyCourse fragmentMyCourse;
    FragmentNotice fragmentShopTab;
    FragmentMainNewsType fragmentNewsTab;
    FragmentMe fragmentMe;
    IndexFragmentAdapter adapter;
    @BindView(R.id.viewpager)
    SuperViewPager viewpager;
    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.lay_home)
    LinearLayout layHome;
    @BindView(R.id.iv_course)
    ImageView ivCourse;
    @BindView(R.id.tv_course)
    TextView tvCourse;
    @BindView(R.id.lay_course)
    LinearLayout layCourse;
    @BindView(R.id.iv_notice)
    ImageView ivNotice;
    @BindView(R.id.tv_notice)
    TextView tvNotice;
    @BindView(R.id.lay_notice)
    LinearLayout layNotice;
    @BindView(R.id.iv_news)
    ImageView ivNews;
    @BindView(R.id.tv_news)
    TextView tvNews;
    @BindView(R.id.lay_news)
    LinearLayout layNews;
    @BindView(R.id.iv_mine)
    ImageView ivMine;
    @BindView(R.id.tv_mine)
    TextView tvMine;
    @BindView(R.id.lay_mine)
    LinearLayout layMine;
    @BindView(R.id.radio)
    LinearLayout radio;

    AdvertisementDialog advertisementDialog;
    MainAdvContract.Presenter advPresenter;
    DownloadContract.Presenter downloadPresenter;
    VersionContract.Presenter versionPresenter;
    NewVersionDialog newVersionDialog;
    File apkFile = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_tab;
    }

    @Override
    protected void initView() {
        viewpager.setEnabled(false);
        fragmentMainTab = FragmentMainBaseType.getInstance();
        fragmentMyCourse = FragmentMyCourse.getInstance();
        fragmentShopTab = FragmentNotice.getInstance();
        fragmentNewsTab = FragmentMainNewsType.getInstance();
        fragmentMe = FragmentMe.getInstance();

        fragmentList.add(fragmentMainTab);
        fragmentList.add(fragmentMyCourse);
        fragmentList.add(fragmentShopTab);
        fragmentList.add(fragmentNewsTab);
        fragmentList.add(fragmentMe);

        adapter = new IndexFragmentAdapter(getSupportFragmentManager(), fragmentList);
        viewpager.setAdapter(adapter);
        viewpager.setOffscreenPageLimit(5);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                changeBottomMenu(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });


//        if(BuildConfig.DEBUG){
//            String a = null;
//            a.toCharArray();
//        }

        UserInfo userInfo = SPUtils.getUserInfo(mContext);
        if (userInfo != null) {
            CrashReport.setUserId(userInfo.getId() + "");
        }
    }

    @Override
    public void initData() {
        super.initData();
        advPresenter = new MainAdvContract.Presenter();
        advPresenter.attachView(this);
        advPresenter.getMainAdv();
        downloadPresenter = new DownloadContract.Presenter();
        downloadPresenter.attachView(this);
        versionPresenter = new VersionContract.Presenter();
        versionPresenter.attachView(this);
        versionPresenter.getVersion();
    }


    @OnClick({R.id.lay_home, R.id.lay_course, R.id.lay_notice, R.id.lay_news, R.id.lay_mine})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.type:
                break;
            case R.id.lay_home:
                changeBottomMenu(0);
                viewpager.setCurrentItem(0);
                break;
            case R.id.lay_course:
                changeBottomMenu(1);
                viewpager.setCurrentItem(1);
                break;
            case R.id.lay_notice:
                changeBottomMenu(2);
                viewpager.setCurrentItem(2);
                break;
            case R.id.lay_news:
                changeBottomMenu(3);
                viewpager.setCurrentItem(3);
                break;
            case R.id.lay_mine:
                changeBottomMenu(4);
                viewpager.setCurrentItem(4);
                break;
        }
    }

    /**
     * 切换底部栏
     */
    public void changeBottomMenu(int position) {
        int orangeColor = getResources().getColor(R.color.themeColor);
        int grayColor = getResources().getColor(R.color.text_sub_title);
        ivHome.setImageResource(R.mipmap.main_home_unselect);
        ivCourse.setImageResource(R.mipmap.main_course_unselect);
        ivNotice.setImageResource(R.mipmap.main_notice_unselect);
        ivNews.setImageResource(R.mipmap.main_news_unselect);
        ivMine.setImageResource(R.mipmap.main_mine_unselect);

        tvHome.setTextColor(grayColor);
        tvCourse.setTextColor(grayColor);
        tvNotice.setTextColor(grayColor);
        tvNews.setTextColor(grayColor);
        tvMine.setTextColor(grayColor);

        switch (position) {
            case 0:
                ivHome.setImageResource(R.mipmap.main_home_selected);
                tvHome.setTextColor(orangeColor);
                break;
            case 1:
                ivCourse.setImageResource(R.mipmap.main_course_selected);
                tvCourse.setTextColor(orangeColor);
                break;
            case 2:
                ivNotice.setImageResource(R.mipmap.main_notice_selected);
                tvNotice.setTextColor(orangeColor);
                break;
            case 3:
                ivNews.setImageResource(R.mipmap.main_news_selected);
                tvNews.setTextColor(orangeColor);
                break;
            case 4:
                ivMine.setImageResource(R.mipmap.main_mine_selected);
                tvMine.setTextColor(orangeColor);
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (adapter != null) {
            BaseMvpFragment fragment = adapter.getCurrentFragment();
            if (fragment == null) {
                return super.dispatchTouchEvent(event);
            }
            if (fragment instanceof FragmentMainBaseType) {
                if (((FragmentMainBaseType) fragment).indexFragmentStateAdapter != null
                        && ((FragmentMainBaseType) fragment).indexFragmentStateAdapter.getCurrentFragment() != null
                ) {
//                    ((FragmentMainTab) ((FragmentMainBaseType) fragment).indexFragmentStateAdapter.getCurrentFragment())
//                            .gesture.onTouchEvent(event);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    public void goIndexpage(int index) {
        changeBottomMenu(index);
        viewpager.setCurrentItem(index);
    }

    boolean isClilckOnce = false;

    @Override
    public void onBackPressed() {
        if (viewpager.getCurrentItem() == 1) {
            viewpager.setCurrentItem(4);
        } else {
            if (isClilckOnce) {
                finish();
            } else {
                XToast.toast(mContext, "再按一次退出APP");
                isClilckOnce = true;
                new Handler().postDelayed(() -> isClilckOnce = false, 1000);
            }
        }
    }

    @Override
    public void setAdv(MainAdv mainAdv) {
        if (mainAdv == null) {
            return;
        }
        int id = SPUtils.getPrefInt(mContext, "main_adv_id", -1);
        if (id != mainAdv.getId()) {
            //id 不同，新广告
            if (advertisementDialog == null) {
                advertisementDialog = new AdvertisementDialog(mContext);
            }
            advertisementDialog.setImage(mainAdv);
            advertisementDialog.show();

        }
    }

    @Override
    public void downloadSuc(File f) {
        this.apkFile = f;
        if (newVersionDialog != null && newVersionDialog.isShowing()) {
            newVersionDialog.dismiss();
            newVersionDialog = null;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean haveInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                //权限没有打开则提示用户去手动打开
                setInstallPermission();
            } else {
                NOpenFiles.openFile(this, f);
            }
        } else {
            NOpenFiles.openFile(this, f);

        }

    }

    @Override
    public void progress(int progress) {
        if (newVersionDialog != null) {
            newVersionDialog.changeProgerss(progress);
        }
    }

    @Override
    public void downloadStart() {

    }

    @Override
    public void downloadError(String msg) {

    }

    @Override
    public void setAppVersion(AppVersionInfo version) {
        int versionCode = SPUtils.getPrefInt(mContext, "main_version_code", -1);

        int myVersion = AppUtil.getVersionCode(mContext);

        if (versionCode == version.getVersion() && myVersion > version.getLowest()) {
            //不强更的只提示一次
            return;
        }
        if (myVersion < version.getVersion()) {
            if (newVersionDialog == null) {
                newVersionDialog = new NewVersionDialog(this);
            }
            newVersionDialog.setDownloadCallback(url -> {

                File dir = new File(FileUtil.getPath(mContext) + "/apk/");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File apkFile = new File(dir.getAbsoluteFile() + "/" + version.getVersion() + ".apk");
                if (apkFile.exists()) {
                    apkFile.delete();
                }
//                downloadPresenter.downloadFile(url, apkFile.getAbsolutePath());
                //切到系统下载

                DownloadManagerUtil.getInstance(mContext).download(url, "一锤公考", "正在下载新版本");
                newVersionDialog.cancel();
            });
            newVersionDialog.show(version, myVersion);
        }
    }


    /**
     * 8.0以上系统设置安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void setInstallPermission() {
        //弹框提示用户手动打开
//        HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "权限申请", "是否允许安装位置来源应用？");
//        hintConfirmDialog.setOkListener(v -> {
//            toInstallPermissionSettingIntent();
//            hintConfirmDialog.dismiss();
//
//        });
//        hintConfirmDialog.setCancelListener(v -> {
//            //
//            hintConfirmDialog.dismiss();
//        });
//        hintConfirmDialog.show();

        toInstallPermissionSettingIntent();
    }


    /**
     * 开启安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void toInstallPermissionSettingIntent() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 1005);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1005) {
//            Toast.makeText(this, "安装应用", Toast.LENGTH_SHORT).show();
            if (apkFile != null) {
                NOpenFiles.openFile(this, apkFile);
            }
        }
    }
}
